package com.bbbug.coree.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbbug.coree.entity.Messageinfo;
import com.bbbug.coree.entity.Roominfo;
import com.bbbug.coree.entity.Userinfo;
import com.bbbug.coree.service.MessageinfoService;
import com.bbbug.coree.service.RooominfoService;
import com.bbbug.coree.service.UserinfoService;
import com.bbbug.coree.utils.MiscUtil;
import com.bbbug.coree.entity.ReturnData;
import com.bbbug.coree.utils.SpringUtils;
import com.bbbug.coree.websocketservice.core;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.yeauty.pojo.Session;

import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@CrossOrigin(origins ="${myweb-path}" )
@RequestMapping("api/message")
public class MessageinfoController {
    @Autowired
    private MessageinfoService service;
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private RooominfoService roominfoService;
    private RedisTemplate redisTemplate= SpringUtils.getBean("redistemp");
    @RequestMapping("getMessageList")
    public ReturnData getMessageList(@RequestBody Map mp){
        return new ReturnData(200,"",service.queryForList(mp.get("room_id").toString()));
    }
    @Value("${myweb-path}")
    String mywebPath;
    @RequestMapping("send")
    public ReturnData send(@RequestBody Map mp){
        String access_token = (String) mp.get("access_token");
        Object at=mp.get("at");
        String msg = (String) mp.get("msg");
        String to= mp.get("to").toString();
        String type=mp.get("type").toString();
        String uid=MiscUtil.verifyToken(access_token);
        if(uid==null) {
            return new ReturnData(401,"请登陆",null);
        }
        BoundHashOperations shutdown = redisTemplate.boundHashOps("shutdown");
        HashMap<String, Long> jinyan = (HashMap<String, Long>) shutdown.get(to);
        if(jinyan!=null&&jinyan.get(uid)!=null){
            if(jinyan.get(uid)>=System.currentTimeMillis()){
                return new ReturnData(403,"你被禁言中！",null);
            }else{
                jinyan.remove(uid);
            }
        }
        JSONObject message=null;
        try {
            msg= URLDecoder.decode(msg, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (type.equals("img")) {
            message = messageimgbuilder(msg, userinfoService.queryById(Integer.parseInt(uid)));
        } else {
            String regex="(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]";
            Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
            Matcher matcher = pattern.matcher(msg);
            if(matcher.find()){
                String tpurl= matcher.group();
                System.out.println("connect"+tpurl);
                if(tpurl.contains(mywebPath)){
                    String[] split = tpurl.split(mywebPath);
                    int i =0;
                    for(String x:split){
                        i=RoomIdreader(x);
                        if(i!=0) {
                            break;
                        }
                    }
                    Roominfo roominfo = roominfoService.queryById(i);
                    if(roominfo!=null){
                        message=messagejumpbuilder(roominfo,userinfoService.queryById(Integer.parseInt(uid)));
                    }else{
                        message=ReadURLmessage(tpurl,uid);
                    }
                }else {
                   message=ReadURLmessage(tpurl,uid);
                }
            }
           if(message==null) {
               message = messagetextbuilder(msg, userinfoService.queryById(Integer.parseInt(uid)),at);
           }
        }
        savemessage(message.get("message_id").toString(),MiscUtil.verifyToken(access_token),"text","channel",to,message.toString(),0,System.currentTimeMillis()/1000,System.currentTimeMillis()/1000);
        SendForALL(to,message.toString());
        if(at!=null&&at.toString().charAt(0)!='f'){
            JSONObject parse = JSON.parseObject(at.toString().replace("=", ":").replace("{", "{\"").replace("}", "\"}").replace(":", "\":\"").replace(",", "\",\""));
            if(parse.get("user_id").equals("1")){
                naotanrobot(msg,MiscUtil.verifyToken(access_token),to);
            }
        }
        return new ReturnData(200,"",null);
    }
    JSONObject ReadURLmessage(String url,String uid){
        JSONObject message=null;
        try {
            HttpResponse execute = HttpUtil.createGet(url).timeout(2000).execute();
            Document parse = Jsoup.parse(execute.body());
            execute.close();
            String content="没有查到该网站信息 但可以进去";
            Elements meta = parse.getElementsByTag("meta");
            for(Element tp:meta){
                if(isContainChinese(tp.attr("content"))){
                    content=tp.attr("content");
                }
                if(tp.attr("name").contains("description")){
                    break;
                }
            }
            message=messagelinkbuilder(parse.title(),content,url,userinfoService.queryById(Integer.parseInt(uid)));
        }catch (Exception e){
            //do nothing
        }
        return message;
    }
    public static Integer RoomIdreader(String before){
        Integer res=0;
        int len=before.length();
        for(int i=0;i<len;i++){
            char c = before.charAt(i);
            if(c>='0'&&c<='9') {
                res=(res*10)+(c-'0');
            }
        }
        return res;
    }
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    @Async
    void naotanrobot(String text,String to,String channel){
        JSONObject message=new JSONObject();
        try {
            text= URLDecoder.decode(text,"GBK");
        } catch (UnsupportedEncodingException e) {
            //do something
        }
        if(text.trim().length()==0){
            message = messagetextbuilder("没事不要艾特", userinfoService.queryById(1),userinfoService.queryById(Integer.parseInt(to)));
        } else {
            if (text.equals("online"))
                message = messagetextbuilder("当前人数:" + core.CHATMAP.get(channel).size(), userinfoService.queryById(1), userinfoService.queryById(Integer.parseInt(to)));
            else if (StrUtil.similar("来五张色图", text) > 0.8)
                message = messagetextbuilder("好", userinfoService.queryById(1), userinfoService.queryById(Integer.parseInt(to)));
            else if (text.contains("sim") && text.split(" ").length == 3)
                message = messagetextbuilder("相似度:" + StrUtil.similar(text.split(" ")[1], text.split(" ")[2]), userinfoService.queryById(1), userinfoService.queryById(Integer.parseInt(to)));
            else if (text.contains("ip")) {
                message = messagetextbuilder("?", userinfoService.queryById(1), userinfoService.queryById(Integer.parseInt(to)));
            }
//            else if(text.contains("queryb")&&text.contains(" "))
//                message=messagebilibilibuilder(text.split(" ")[1], userinfoService.queryById(1));
            else {
                try {
                    URL url = new URL("http://i.itpk.cn/api.php?question=" + text + "&api_key=35107ba8064678b5534aab5f5e8c982e&api_secret=35oy1p31mm3p&limit=8");
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream(),"UTF-8"));
                    String s = bufferedReader.readLine();
                    try{
                        JSONObject jsonObject = JSON.parseObject(s);
                        s=jsonObject.get("content").toString();
                    }catch (Exception ignored){
                    }
                    message = messagetextbuilder(s, userinfoService.queryById(1), userinfoService.queryById(Integer.parseInt(to)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        savemessage(message.get("message_id").toString(),"1","text","channel",channel,message.toString(),0,System.currentTimeMillis()/1000+1,System.currentTimeMillis()/1000+1);
        SendForALL(channel,message.toString());
    }
    JSONObject messageimgbuilder(String imgurl, Userinfo userinfo){
        JSONObject res = new JSONObject();
        res.put("type","img");
        res.put("content",imgurl);
        res.put("resource",imgurl);
        res.put("at",false);
        res.put("message_time",System.currentTimeMillis()/1000);
        res.put("where","channel");
        res.put("message_id", MiscUtil.NextId());
        res.put("user",userinfo);
        return res;
    }
    JSONObject messagelinkbuilder(String title,String content,String url,Userinfo userinfo){
        JSONObject res = new JSONObject();
        res.put("type","link");
        res.put("link",url);
        res.put("title",title);
        res.put("message_time",System.currentTimeMillis()/1000);
        res.put("desc",content);
        res.put("message_id", MiscUtil.NextId());
        res.put("user",userinfo);
        return res;
    }

//    JSONObject messagebilibilibuilder(String av_bv,Userinfo userinfo){
//        JSONObject res = new JSONObject();
//        res.put("type","bliblivideo");
//        res.put("content","//player.bilibili.com/player.html?aid="+av_bv+"&bvid="+av_bv+"&cid=339139384&page=1");
//        res.put("resource","//player.bilibili.com/player.html?aid="+av_bv+"&bvid="+av_bv+"&cid=339139384&page=1");
//        res.put("at",false);
//        res.put("message_time",System.currentTimeMillis()/1000+1);
//        res.put("where","channel");
//        res.put("message_id", RandomUtil.randomInt(60000000,70000000));
//        res.put("user",userinfo);
//        return res;
//    }

    JSONObject messagetextbuilder(String text, Userinfo userinfo,Object at){
        JSONObject res = new JSONObject();
        res.put("type","text");
        res.put("content",text);
        res.put("resource",text);
        if(at.toString().equals("false")) {
            res.put("at",false);
        } else {
            res.put("at",at);
        }
        res.put("message_time",System.currentTimeMillis()/1000);
        res.put("where","channel");
        res.put("message_id", MiscUtil.NextId());
        res.put("user",userinfo);
        return res;
    }
    JSONObject messagejumpbuilder(Roominfo roominfo, Userinfo userinfo){
        JSONObject res = new JSONObject();
        res.put("type","jump");;
        res.put("jump",roominfo);
        res.put("message_time",System.currentTimeMillis()/1000);
        res.put("message_id",MiscUtil.NextId());
        res.put("user",userinfo);
        return res;
    }


    public boolean savemessage(String messageid,String message_user,String message_type,String message_where,String message_to,String message_content,int message_status,long message_createtime,long message_updatetime){
        Messageinfo messageinfo = new Messageinfo();
        messageinfo.setMessage_id(messageid);
        messageinfo.setMessage_user(Integer.parseInt(message_user));
        messageinfo.setMessage_type(message_type);
        messageinfo.setMessage_where(message_where);
        messageinfo.setMessage_to(Integer.parseInt(message_to));
        messageinfo.setMessage_content(message_content);
        messageinfo.setMessage_status(message_status);
        messageinfo.setMessage_createtime(message_createtime);
        messageinfo.setMessage_updatetime(message_updatetime);
        return service.insert(messageinfo);

    }
    public boolean delmessage(String messageid){
        return service.deleteById(messageid);
      }
    @RequestMapping("back")
    public ReturnData deletemessage(@RequestBody Map map){
        String message_id = map.get("message_id").toString();
        String access_token=map.get("access_token").toString();
        String s = MiscUtil.verifyToken(access_token);
        if(s==null||delmessage(message_id)==false){
            return new ReturnData(401,"失败",null);
        }
        JSONObject message = messagebackbuilder(message_id, userinfoService.queryById(Integer.parseInt(s)));
        SendForALL(map.get("room_id").toString(),message.toString());
        ReturnData returnData = new ReturnData(200, "撤回成功",null);
        return returnData;
    }
    JSONObject messagebackbuilder(String id,Userinfo userinfo){
        JSONObject res = new JSONObject();
        res.put("message_id",id);
        res.put("type","back");
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        res.put("time",format.format(new Date()));
        res.put("user",userinfo);
        return res;
    }
    @RequestMapping("touch")
    ReturnData touch(@RequestBody Map mp){
        String at = mp.get("at").toString();
        String room_id=mp.get("room_id").toString();
        String access_token=mp.get("access_token").toString();
        String s = MiscUtil.verifyToken(access_token);
        if(s==null){
            return new ReturnData(401,"拍不动",null);
        }
        String s1 = Paiyipaibuilder(userinfoService.queryById(Integer.parseInt(s)), userinfoService.queryById(Integer.parseInt(at))).toString();
        SendForALL(room_id,s1);
         return new ReturnData(200,"拍好了",null);
    }

    JSONObject Paiyipaibuilder(Userinfo from,Userinfo to){
        Map map=new HashMap();
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        map.put("time",format.format(new Date()));
        map.put("type","touch");
        map.put("user",from);
        map.put("at",to);
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(map);
        return jsonObject;
    }

    void SendForALL(String room_id, String message) {

        ConcurrentHashMap<String, Session> stringSessionConcurrentHashMap = core.CHATMAP.get(room_id);
            if (stringSessionConcurrentHashMap == null) {
                return;
            }
            for (Session value : stringSessionConcurrentHashMap.values()) {
                value.sendText(message);
            }
    }
    @RequestMapping("clear")
    ReturnData clearALL(@RequestBody Map mp){
        Object access_token = mp.get("access_token");
        if(MiscUtil.verifyToken(access_token.toString())==null){
            return new ReturnData(403,"无权删除",null);
        }
        boolean flag = service.deleteByroomid(Integer.parseInt(mp.get("room_id").toString()));
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("type","clear");
        jsonObject.put("user",userinfoService.queryById(Integer.parseInt(MiscUtil.verifyToken(access_token.toString()))));
        SendForALL(mp.get("room_id").toString(),jsonObject.toJSONString());
        return new ReturnData(200,flag==false?"删除失败":"删除成功",null);
    }

}